package com.ruoyi.system.interAttr.attr;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.interAttr.domain.GamesRes;
import com.ruoyi.system.interAttr.domain.InterAttrRes;
import com.ruoyi.system.interAttr.domain.InterServerRes;
import com.ruoyi.system.model.domain.SalePartner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Encoder;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 密码游戏列表没有接口
 *
 * 等对面开发人员写好   2024 06 27
 *
 */
@Slf4j
@Service
public class KANKANAttr implements AdapterAttr {

    public static String hmacSHA256(String data, String secret) {
        try {
            // Create HMAC-SHA256 key from the given secret
            SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256");

            // Get an instance of Mac object implementing HMAC-SHA256
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(secretKeySpec);

            // Calculate the HMAC value
            byte[] hmacBytes = mac.doFinal(data.getBytes());

            // Convert result into a hexadecimal string
            StringBuilder sb = new StringBuilder(hmacBytes.length * 2);
            for (byte b : hmacBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("Failed to calculate HMAC-SHA256", e);
        }
    }

    public static void main(String[] args) {
        String url = "https://api2.kkzhw.com/mall-portal/openapi/import/product/meta?gameName="+"英雄联盟";
        String time = String.valueOf(System.currentTimeMillis());
        String cover = time+"gameName="+"英雄联盟";
        String sign = hmacSHA256(cover, "LLdDBjVqsAxCyzMhXyAivHjjRDwpWrVy");
        String response = HttpRequest.get(url).header("X-KK-APIKEY", "YmqruNhrVENaEsTb").header("X-KK-TIME", time).header("X-KK-SIGNATURE", sign)
                .execute().body();
        System.out.println(response);
    }

    @Override
    public List<GamesRes> getGames(SalePartner salePartner) {
        String url = "https://api2.kkzhw.com/mall-portal/openapi/import/product/list";
        String time = String.valueOf(System.currentTimeMillis());
        String cover = time;
        String sign = hmacSHA256(cover, "LLdDBjVqsAxCyzMhXyAivHjjRDwpWrVy");

        String response = HttpRequest.get(url).header("X-KK-APIKEY", "YmqruNhrVENaEsTb").header("X-KK-TIME", time).header("X-KK-SIGNATURE", sign)
                .execute().body();

        List<JSONObject> jsonObjects = JSONObject.parseArray(JSONObject.parseObject(response).getString("data"), JSONObject.class);
        List<GamesRes> gamesResList = new ArrayList<>();

        for (JSONObject jsonObject : jsonObjects) {
            GamesRes gamesRes = new GamesRes();
            String id = jsonObject.getString("id");
            String title = jsonObject.getString("name");
            gamesRes.setId(id);
            gamesRes.setGameName(title);
            gamesResList.add(gamesRes);
        }
        return gamesResList;
    }

    @Override
    public List<InterServerRes> getServer(String gameId, SalePartner salePartner) {
        String gameName = "";
        List<GamesRes> games = getGames(salePartner);
        for(GamesRes gamesRes : games){
            if(gameId.equals(gamesRes.getId())){
                gameName = gamesRes.getGameName();
            }
        }
        String url = "https://api2.kkzhw.com/mall-portal/openapi/import/product/meta?gameName="+gameName;
        String time = String.valueOf(System.currentTimeMillis());
        String cover = time+"gameName="+gameName;
        String sign = hmacSHA256(cover, "LLdDBjVqsAxCyzMhXyAivHjjRDwpWrVy");
        String response = HttpRequest.get(url).header("X-KK-APIKEY", "YmqruNhrVENaEsTb").header("X-KK-TIME", time).header("X-KK-SIGNATURE", sign)
                .execute().body();
        String data = JSONObject.parseObject(response).getString("data");
        String extGameAttributeArrays = JSONObject.parseObject(data).getString("extGameAttributeArrays");
        List<JSONObject> extGameArray = JSONObject.parseArray(extGameAttributeArrays, JSONObject.class);
        JSONObject jsonObject = extGameArray.get(0);
        List<InterServerRes> interServerRes = new ArrayList<>();
        String inputList = jsonObject.getString("inputList");
        if(!inputList.contains("[{")){

            String[] split = inputList.split(",");
            for (String datum : split) {
                InterServerRes interServer = new InterServerRes();
                interServer.setId(datum);
                interServer.setName(datum);
                interServerRes.add(interServer);
            }
        }else {
            JSONArray jsonArray = JSONArray.parseArray(inputList);
            for(Object o : jsonArray){
                InterServerRes interServer = new InterServerRes();
                interServer.setId(JSONObject.parseObject(o.toString()).getString("parent_name"));
                interServer.setName(JSONObject.parseObject(o.toString()).getString("parent_name"));
                String childList = JSONObject.parseObject(o.toString()).getString("childList");
                List<String> jsonObjects = JSONObject.parseArray(childList, String.class);
                List<InterServerRes> interServerRes1 = new ArrayList<>();
                for(String s : jsonObjects){
                    InterServerRes interServer1 = new InterServerRes();
                    interServer1.setId(s);
                    interServer1.setName(s);
                    interServerRes1.add(interServer1);
                }
                interServer.setInterServerRes(interServerRes1);
                interServerRes.add(interServer);
            }
        }
        return interServerRes;
    }

    @Override
    public List<InterAttrRes> getPropety(String gameId, String type, SalePartner salePartner) {
        String gameName = "";
        List<GamesRes> games = getGames(salePartner);
        for(GamesRes gamesRes : games){
            if(gameId.equals(gamesRes.getId())){
                gameName = gamesRes.getGameName();
            }
        }
        String url = "https://api2.kkzhw.com/mall-portal/openapi/import/product/meta?gameName="+gameName;
        String time = String.valueOf(System.currentTimeMillis());
        String cover = time+"gameName="+gameName;
        String sign = hmacSHA256(cover, "LLdDBjVqsAxCyzMhXyAivHjjRDwpWrVy");
        String response = HttpRequest.get(url).header("X-KK-APIKEY", "YmqruNhrVENaEsTb").header("X-KK-TIME", time).header("X-KK-SIGNATURE", sign)
                .execute().body();
        String datas = JSONObject.parseObject(response).getString("data");
        String extGameAttributeArrays = JSONObject.parseObject(datas).getString("extGameAttributeArrays");
        List<InterAttrRes> interAttrResList = new ArrayList<>();
        List<JSONObject> data = JSONObject.parseArray(extGameAttributeArrays, JSONObject.class);
        data = data.subList(1,data.size());
        List<JSONObject> collect = new ArrayList<>();
        if (Objects.equals("1",type)){
            collect = data.stream().collect(Collectors.toList());
        }else if  (Objects.equals("2",type)){
            collect = data.stream().collect(Collectors.toList());
        }else if (Objects.equals("3",type)){
            collect = data.stream().collect(Collectors.toList());
        }
        for (JSONObject object : collect) {
            String inputList = object.getString("inputList");
            String[] split = inputList.split(",");
            InterAttrRes interAttrRes = new InterAttrRes();
            interAttrRes.setId(object.getString("name"));
            interAttrRes.setName(object.getString("name"));
            List<InterAttrRes> interAttrResList1 = new ArrayList<>();
            for(String o : split) {
                InterAttrRes interAttrRes1 = new InterAttrRes();
                interAttrRes1.setId(o);
                interAttrRes1.setName(o);
                interAttrResList1.add(interAttrRes1);
                interAttrRes.setInterServerRes(interAttrResList1);
            }
            interAttrResList.add(interAttrRes);
        }
        return interAttrResList;
    }
}